package com.bringway.global.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.bringway.framework.controller.JsonController;
import com.bringway.framework.domain.SysAttechment;
import com.bringway.framework.exception.ServiceException;
import com.bringway.framework.util.DateUtils;
import com.bringway.framework.util.FileUtils;
import com.bringway.framework.util.RequestUtils;
import com.bringway.framework.util.ftp.FtpUtil;
import com.bringway.global.domain.SysUserDetails;
import com.bringway.global.domain.User;
import com.bringway.global.service.SysAttechmentService;

import net.sf.json.JSONObject;

/*
* @author 作者 xuef
* @version 创建时间：2015年9月11日 下午4:20:48
* 类说明
*/
@Controller
@RequestMapping("/upload")
public class UploadController extends JsonController{
	@Autowired
	private SysAttechmentService attechmentService;
	
	private static final long UPLOAD_FILE_SIZE =30971520;
	
	/***
	 * execute upload
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest)request;
		CommonsMultipartFile file = (CommonsMultipartFile)mrequest.getFile("file");
		FileItem fileItem = file.getFileItem();
		fileItem.getInputStream();
		
		if (UPLOAD_FILE_SIZE < new Long(file.getSize()).longValue()){
			throw new ServiceException("只能上传30M以内的附件！");
		}
		
		String orgId = RequestUtils.getStringParameter(request, "orgId");
		
		String ftpPath ="";
		try {
			ftpPath = FtpUtil.upload(orgId,file.getInputStream());
		} catch (IOException e) {
			throw new ServiceException("文件上传失败!");
		}
		
		SysAttechment sysAttechment = createSysAttechment(fileItem,request);
		sysAttechment.setFtpPath(ftpPath);//设置FTP路径
		Long id = attechmentService.createSysAttechment(sysAttechment);
		
		JSONObject result = new JSONObject();
		result.put("FILE_ID", id+"");
		result.put("FILE_NAME", sysAttechment.getFileName());
		result.put("FILE_SIZE", sysAttechment.getSize()+"");
		result.put("UPLOAD_USERNAME", sysAttechment	.getUploadUserName());
		result.put("UPLOAD_TIME", DateUtils.toString(sysAttechment.getUploadTime(),"yyyy-MM-dd HH:mm:ss"));
		result.put("success", Boolean.TRUE);
		serialize(request,response,result);
	}
	
//	/***
//	 * 照片上传
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String userName = AppUtils.getCurrentUserInfo(request).getUserName();
//		Long userId = AppUtils.getCurrentUserInfo(request).getUserId();
//		String fileName = request.getParameter("picSer");
//		String orgId = request.getParameter("orgId");
//		InputStream in = request.getInputStream();
//		
//		String ftpPath = "";
//		try {
//			ftpPath = FtpUtil.upload(orgId,in);
//		} catch (Exception e) {
//			throw new ServiceException("文件上传失败!");
//		}
//		
//		SysAttechment sysAttechment = new SysAttechment();
//		sysAttechment.setContextType("image/pjpeg");
//		sysAttechment.setFileName(fileName);
//		sysAttechment.setFtpPath(ftpPath);
//		sysAttechment.setSize(0);
//		sysAttechment.setUploadTime(new Date());
//		sysAttechment.setUploadUserId(userId);
//		sysAttechment.setUploadUserName(userName);
//		attechmentService.createSysAttechment(sysAttechment);
//		
//		FormResult result = new FormResult();
//		result.setSuccess(true);
//		serialize(response, result);
//		
//	}
//
	public SysAttechment createSysAttechment(FileItem fileItem,HttpServletRequest request) throws IOException{
		SysUserDetails sysUserDetails =	(SysUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		SysAttechment sysAttechment = new SysAttechment();
		sysAttechment.setContextType(fileItem.getContentType());
		sysAttechment.setFileName(FileUtils.getName(fileItem.getName()));
		sysAttechment.setSize(fileItem.getSize());
		sysAttechment.setUploadTime(new Date());
		sysAttechment.setUploadUserId(null!=sysUserDetails?sysUserDetails.getGyh():"");
		sysAttechment.setUploadUserName(null!=sysUserDetails?sysUserDetails.getUsername():"");
		return sysAttechment;
	}
	
	/***
	 * list Files
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("listFiles")
	public void listFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String bizId = RequestUtils.getStringParameter(request,"bizId");
		Collection list = attechmentService.listAllAttByBizId(bizId);
		List resultList = new ArrayList();
		for(Iterator it = list.iterator();it.hasNext();){
			SysAttechment sysAtt = (SysAttechment)it.next();
			Map result = new HashMap();
			result.put("FILE_ID", sysAtt.getId()+"");
			result.put("FILE_NAME", sysAtt.getFileName());
			result.put("FILE_SIZE", sysAtt.getSize()+"");
			result.put("UPLOAD_USERNAME", sysAtt.getUploadUserName());
			result.put("UPLOAD_TIME", DateUtils.toString(sysAtt.getUploadTime(),"yyyy-MM-dd HH:mm:ss"));
			resultList.add(result);
		}
		serialize(request,response,resultList,true);
	}
	
	/***
	 * downFile
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("downloadFile")
	public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String attachId = RequestUtils.getStringParameter(request, "attachId");
		SysAttechment att = attechmentService.getSysAttechment(attachId);
		if(att != null){
			response.reset();
			response.setContentType(att.getContextType());
			response.setHeader("Content-Disposition", "attachment;filename=\""+new String(att.getFileName().getBytes("GBK"),"ISO-8859-1") +"\"");
			FtpUtil.download(att.getFtpPath(), response.getOutputStream());
		}
	}
//	
//	/***
//	 * 下载图片
//	 * @param request
//	 * @param response
//	 * @throws Exception
//	 */
//	public void downloadPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String fileName = RequestUtils.getStringParameter(request, "picSer");
//		SysAttechment att = attechmentService.getSysAttechmentByFileName(fileName);
//		if(att != null){
//			response.reset();
//			response.setContentType(att.getContextType());
//			response.setHeader("Content-Disposition", "attachment;filename="+new String(att.getFileName().getBytes("GBK"),"ISO-8859-1"));
//			FtpUtil.download(att.getFtpPath(), response.getOutputStream());
//		}
//	}
//	
//	public void deletePic(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String fileName = RequestUtils.getStringParameter(request, "pId");
//		attechmentService.delAttByFileName(fileName);
//		serialize(response, Boolean.TRUE);
//	}
//
//	public void execute(HttpServletRequest request, HttpServletResponse response)
//			throws Exception {
//		// TODO Auto-generated method stub
//		
//	}	


}
